package com.googlecode.hyakutaded;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import com.googlecode.hyakutaded.json.JSONException;
import com.googlecode.hyakutaded.json.JSONObject;

public class PollServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Clients clients = Clients.getInstance();
	private long TIMEOUT = 22000;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String clientId = req.getParameter("clientId");
		String packetIdString = req.getParameter("packetId");
		long packetId = 0;
		if (clientId != null) {
			Client c = clients.getClient(clientId);
			try {
				packetId = Long.parseLong(packetIdString);
			} catch (Exception e) {
				packetId = 0;
			}
			Continuation continuation = ContinuationSupport.getContinuation(
					req, c);
			JSONObject response;
			try {
				response = c.getPacket(packetId, continuation, TIMEOUT)
						.getContent();
				resp.setContentType("application/json");
				response.write(resp.getWriter());

			} catch (JSONException e) {
				throw new ServletException(e.getMessage(), e);
			}
		}
	}

}
